package com.czh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czh.constants.SystemConstants;
import com.czh.domain.ResponseResult;
import com.czh.domain.entity.RoleMenu;
import com.czh.domain.vo.MenuAuthorityVo;
import com.czh.domain.vo.MenuOldVo;
import com.czh.domain.vo.MenuPageVo;
import com.czh.domain.vo.MenuTreeVo;
import com.czh.enums.AppHttpCodeEnum;
import com.czh.mapper.MenuMapper;
import com.czh.domain.entity.Menu;
import com.czh.service.MenuService;
import com.czh.service.RoleMenuService;
import com.czh.utils.BeanCopyPlusUtils;
import com.czh.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 菜单权限表(Menu)表服务实现类
 *
 * @author makejava
 * @since 2024-03-28 20:41:37
 */
@Service("menuService")
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {
    @Resource
    private RoleMenuService roleMenuService;
    /**
     * 根据用户id查询权限
     *
     * @param id 用户id
     * @return 权限列表
     */
    @Override
    public List<String> selectPermsByUserId(Long id) {
        //因为表中没有用户id1，所以这里直接返回所有的权限
        if (id == 1) {
            LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(Menu::getMenuType, SystemConstants.MENU, SystemConstants.BUTTON);
            queryWrapper.eq(Menu::getStatus, SystemConstants.MENU_STATUS_NORMAL);
            List<Menu> menuList = list(queryWrapper);
            return menuList.stream().map(Menu::getPerms).collect(Collectors.toList());
        }
        return getBaseMapper().selectPermsByUserId(id);
    }

    /**
     * 根据用户id查询菜单
     * @param userId 用户id
     * @return 菜单列表
     */
    @Override
    public List<Menu> selectRouterMenuTreeByUserId(Long userId) {
        MenuMapper menuMapper = getBaseMapper();
        ArrayList<Menu> menus;
        if (SecurityUtils.isAdmin()) {
            menus = menuMapper.selectRouterMenuAll();
        } else {
            menus = menuMapper.selectRouterMenuById(userId);
        }
        return builderMenuTree(menus, 0L);
    }

    public ResponseResult<List<MenuTreeVo>> getRoleMenuTree() {
        ArrayList<Menu> menus = getBaseMapper().selectRouterMenuAll();
        List<MenuTreeVo> menuTree = BeanCopyPlusUtils.copyPropertiesList(menus, MenuTreeVo.class);
        List<MenuTreeVo> menuTreeVos = builderRoleMenuTree(menuTree, 0L);
        return ResponseResult.okResult(menuTreeVos);
    }

    @Override
    public ResponseResult<MenuAuthorityVo> getMenuTreeById(Long id) {
        List<Menu> menus = getBaseMapper().selectRouterMenuAll();
        LambdaQueryWrapper<RoleMenu> roleMenuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //获取角色对应的菜单id
        roleMenuLambdaQueryWrapper.eq(RoleMenu::getRoleId, id);
        if(id==1L){
            roleMenuLambdaQueryWrapper=null;
        }
        List<Long> menuIds = roleMenuService.list(roleMenuLambdaQueryWrapper).stream().
                map(RoleMenu::getMenuId).collect(Collectors.toList());
        List<MenuTreeVo> menuTrees = BeanCopyPlusUtils.copyPropertiesList(menus, MenuTreeVo.class);
        List<MenuTreeVo> menuTreeVos = builderRoleMenuTree(menuTrees, 0L);
        return ResponseResult.okResult(new MenuAuthorityVo(menuTreeVos, menuIds));
    }

    @Override
    public ResponseResult<List<MenuPageVo>> getMenuList(String status, String menuName) {
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Objects.nonNull(status), Menu::getStatus, status).like(Objects.nonNull(menuName), Menu::getMenuName, menuName);
        List<MenuPageVo> menuPageVos = BeanCopyPlusUtils.copyPropertiesList(list(queryWrapper), MenuPageVo.class);
        return ResponseResult.okResult(menuPageVos);
    }

    @Override
    public ResponseResult<Object> addMenu(Menu menu) {
        save(menu);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult<Object> deleteMenu(Long menuId) {
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Menu::getParentId, menuId);
        if (count(queryWrapper)>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DELETE_ERROR);
        }else {
            removeById(menuId);
            return ResponseResult.okResult();
        }
    }

    @Override
    public ResponseResult<MenuOldVo> getMenuById(Long id) {
        MenuOldVo menuOldVo = BeanCopyPlusUtils.copyProperties(getById(id), MenuOldVo.class);
        return ResponseResult.okResult(menuOldVo);
    }

    @Override
    public ResponseResult<Object> updateMenu(Menu menu) {
        if (Objects.equals(menu.getMenuName(), getById(menu.getParentId()).getMenuName())){
            return ResponseResult.errorResult(AppHttpCodeEnum.UPDATE_ERROR);
        }
        updateById(menu);
        return ResponseResult.okResult();
    }

    /**
     * 递归构建菜单树
     * @param menuTreeVos 菜单列表
     * @param parentId    父菜单ID
     * @return 菜单树
     */
    public List<MenuTreeVo> builderRoleMenuTree(List<MenuTreeVo> menuTreeVos, long parentId) {
        return menuTreeVos.stream().filter(menuTreeVo -> menuTreeVo.getParentId() == parentId).
                map(menuTreeVo -> menuTreeVo.setChildren(builderRoleMenuTree(menuTreeVos, menuTreeVo.getId()))).
                collect(Collectors.toList());
    }

    /**
     * 递归构建菜单树
     * @param menus    菜单列表
     * @param parentId 父菜单ID
     * @return 菜单树
     */
    public List<Menu> builderMenuTree(List<Menu> menus, long parentId) {
        return menus.stream().
                filter(menu -> menu.getParentId().equals(parentId)).
                map(menu -> menu.setChildren(builderMenuTree(menus, menu.getId()))).
                collect(Collectors.toList());
    }
}

